package ext.tianma.part.finishedProduct.util;

import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import wt.csm.navigation.ClassificationNode;
import wt.csm.navigation.litenavigation.ClassificationNodeDefaultView;
import wt.csm.navigation.service.ClassificationObjectsFactory;
import wt.iba.definition.litedefinition.AttributeDefDefaultView;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.type.ClientTypedUtility;
import wt.util.WTException;

import com.alibaba.fastjson.JSON;

import ext.generic.erp.common.CommonUtil;
import ext.tianma.bom.util.CSCIBA;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.part.Interface.MDMCheckInterface.Bean.PartCheckBean;
import ext.tianma.part.Interface.MDMCheckInterface.Bean.PartCheckInformationSendBean;
import ext.tianma.part.Interface.MDMCheckInterface.Bean.SendBean;
import ext.tianma.part.Interface.MDMCheckInterface.Service.PartCheckService;
import ext.tianma.part.Interface.MDMCheckInterface.Service.PartCheckServiceToSOA;
import ext.tianma.util.PropertiesUtil;

public class InterfaceUtil {
	
	private static Logger log = LogR.getLogger(InterfaceUtil.class.getName());
	
	public static boolean sendCheckService(WTPart part, Map<String, String> classAttrsMap,ClassificationNode node) throws RemoteException, WTException {
		log.debug("InterfaceUtil:sendCheckService==>>Start:partNumber"+part.getNumber());
		log.debug("classAttrsMap=="+classAttrsMap);
		try {
			PartCheckBean partBean = new PartCheckBean();
			PropertiesUtil ut = new PropertiesUtil(PartCheckService.path);
			// 名称
			partBean.setPartName(part.getName());
			// 料号
			partBean.setPartNumber(part.getNumber());
			// 物料类别
			String partType = ClientTypedUtility.getLocalizedTypeName(part, Locale.CHINA);
			partBean.setPartType(partType);
			// 分类路径对应的MDM的分类代码
			ClassificationNodeDefaultView cndv = ClassificationObjectsFactory.newClassificationNodeDefaultView(node);
	    	String fullPath = CSMUtil.getClassificationFullPath(cndv);
			//String classification = ClassificationUtil.getClassification(part);
	    	fullPath = PartCheckService.replaceBlank(fullPath);
			String code = ut.getValueByKey(fullPath);
			if (StringUtil.isNullOrEmpty(code)) {
				throw new WTException("分类对应的值为空!请确认所选的分类是否正确!");
			}
			partBean.setClassification(code);
			// 分类属性集合
			partBean.setClassificationList(classAttrsMap);

			SendBean sendBean = new SendBean();
			sendBean.setParts(partBean);
			// 封装发送信息
			PartCheckInformationSendBean check = new PartCheckInformationSendBean();
			check.setServiceInterfaceCode("ESBSDPH0005");
			check.setFromSystemCode("101SDP");
			check.setFromInterfaceCode("");
			check.setToInterfaceCode("MDMH0002");
			check.setOuZone("OU_TMSH");
			check.setFactoryName("");
			check.setUuid("653ab555e56909e754f0b1c359283069");
			String time = CommonUtil.getCurrentTime();
			check.setRequestTime(time);
			check.setUserName("");
			check.setPassword("");
			check.setSign("");
			check.setDataType("JSON");
			check.setData(sendBean);

			String result2 = JSON.toJSONString(check);

			// url post发布物料信息
			String result = PartCheckServiceToSOA.sendPartCheckBean(result2);
			log.debug("调用接口返回的结果==> " + result);
			if (!StringUtil.isNullOrEmpty(result)) {
				// 二级物料接口返回值的校验
				JSONObject object;
				object = new JSONObject((String) result.toString());
				System.out.println("返回值:" + object);
				if (object.has("resultCode")) {

					/*
					 * {"resultCode":"1","resultMsg":null}
					 */
					String resultCode = object.getString("resultCode");

					if ("1".equals(resultCode)) {

					} else {
						JSONObject resultData = object.getJSONObject("resultData");
						if (!(resultData == null)) {
							JSONArray dataInfo = resultData.getJSONArray("dataInfo");
							String string = "";
							for (int i = 0; i < dataInfo.length(); i++) {
								JSONObject ob = (JSONObject) dataInfo.get(i);
								if (ob.has("synResult")) {
									String synResult = ob.getString("synResult");
//										string = string + synResult;
									
//										//测试
//										String synResult = "\"BLY色度YMax\"：必须为浮点类型;\"LED灯数量\"：必须为浮点类型;\"产品尺寸\"：必须为浮点类型;";
									
									string = getMessageInfo(synResult, classAttrsMap);
									log.debug("返回到前端页面值==> " + string);
								}
							}
							if(!StringUtil.isNullOrEmpty(string)) {
								throw new WTException(string);									
							}
						}
					}
				}
				return true;
			} else {
				throw new WTException("调用MDM接口:主数据校验数据接口失败!");
			}
		} catch (JSONException e) {
			e.printStackTrace();
			throw new WTException("调用MDM接口:主数据校验数据接口失败!");
		}
	}

	/**
	 * 匹配提示内容
	 * @param synResult
	 * @param maps
	 * @return
	 */
	private static String getMessageInfo(String synResult, Map<String, String> classAttrsMap) {
		
		/**
		 * "synResult": "\"BLY色度YMax\"：必须为浮点类型;\"LED灯数量\"：必须为浮点类型;\"产品尺寸\"：必须为浮点类型;"
		 * 
		 * maps：
		 * 		key:分类属性key
		 * 		value：分类属性value
		 * */
		
		Map<String, String> messageInfo = analyResult(synResult);
		
		log.debug("messageInfo map==> " + messageInfo);
		AttributeDefDefaultView attributedefdefaultview;
		StringBuffer sbf = new StringBuffer();
		
        for(String messageKey : messageInfo.keySet()) {
        	for(String key : classAttrsMap.keySet()) {
    			attributedefdefaultview = CSCIBA.getAttributeDefinition(key);
    			String displayName = attributedefdefaultview.getDisplayName();
    			if(displayName.contains(messageKey)){
    				String message = messageInfo.get(messageKey);
	    		    sbf.append(displayName).append(":").append(message).append(";;");//每一条提示，以双封号;;分割
        		}
        	}
		}		
		return sbf.toString();
	}
	
	/**
	 * 封装下游接口返回的提示信息
	 * @param synResult
	 * @return
	 */
	private static Map<String, String> analyResult(String synResult) {
		/**
		 * "synResult": "\"产品尺寸1\"：必须为浮点类型;\"产品尺寸2\"：必须为浮点类型;\"产品尺寸3\"：必须为浮点类型;;"
		 * 
		 * result:
		 * 	产品尺寸1:必须为浮点类型
		 * 	产品尺寸2:必须为浮点类型
		 * 	产品尺寸3:必须为浮点类型
		 * 
		 * */
		Map<String, String> resultMap = new HashMap<String, String>();
		String [] results = synResult.replace("；", ";").split(";");//防止中英文编码问题
		for(String result : results) {
			String [] r = result.replace("：", ":").split(":");
			String displayName = r[0].replaceAll("\"", "");//如果接口传递字符串含有引号，移除掉,防止与真正的属性名称不匹配
			String message = "";
			for(int i = 1;i<r.length;i++){
				message = message + r[i] + ":";
			}
			if(StringUtils.isNotEmpty(message)){
				message = message.substring(0, message.length()-1);
			}
			resultMap.put(displayName, message);
		}
		return resultMap;
	}
}
